package com.waijiaojun.tpo.web.weixin;

import com.waijiaojun.tpo.service.weixin.WeixinH5payNotifyService;
import com.waijiaojun.tpo.utils.Constants;
import com.waijiaojun.tpo.utils.WxPayReturnCode;
import com.waijiaojun.tpo.utils.XmlUtil;
import com.waijiaojun.tpo.vo.wx.response.PayNotifyResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 会员卡 链接回调 Controller
 *
 * @author Peter
 */
@Controller
@RequestMapping(value = "/weixin-pay-callback")
public class WeixinH5PayCallbackController {

    private static Logger logger = LoggerFactory.getLogger(WeixinH5PayCallbackController.class);

    @Autowired
    private WeixinH5payNotifyService weixinH5payNotifyService;

    // custom_field1_url 等级
    @RequestMapping(value = "pay-notify", method = RequestMethod.POST)
    @ResponseBody
    public String payNotify(@RequestBody String xml, HttpServletRequest request, HttpServletResponse response, Model model) {
        logger.info(Constants.prefix_in + xml);

        PayNotifyResponse resp = null;
        try {
            resp = weixinH5payNotifyService.processPayNotify(xml);
        } catch (Exception e) {
            resp = new PayNotifyResponse();
            resp.setReturn_code(WxPayReturnCode.FAIL);
            resp.setReturn_msg("Error");
            logger.error(e.getMessage(), e);
        }
        String reponseXml = XmlUtil.toXml(resp);
        logger.info(Constants.prefix_out + reponseXml);
        return reponseXml;
    }

}
